package com.leyou.sms.utils;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.leyou.common.constants.SmsConstants;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.sms.config.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class MsgHelper {

    @Autowired
    private IAcsClient client;

    @Autowired
    private SmsProperties prop;

    public void sendCode(String phone, String code){
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(prop.getDomain());
        request.setSysVersion(prop.getVersion());
        request.setSysAction(prop.getAction());
        request.putQueryParameter(SmsConstants.SMS_PARAM_REGION_ID, prop.getRegionID());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_PHONE, phone);
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_SIGN_NAME, prop.getSignName());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_CODE, prop.getVerifyCodeTemplate());
        request.putQueryParameter(SmsConstants.SMS_PARAM_KEY_TEMPLATE_PARAM, "{\""+prop.getCode()+"\":\""+code+"\"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            //将发短信的返回结果转成map
            Map<String, String> respMap = JsonUtils.toMap(response.getData(), String.class, String.class);
            //判断返回结果的Code是否为OK
            if(StringUtils.equals(respMap.get(SmsConstants.SMS_RESPONSE_KEY_CODE), SmsConstants.OK)){
                log.info("【阿里云短信工具类】发送短信成功，手机用户"+phone+"已经接收到了验证码！");
                return;
            }
            log.error("【阿里云短信工具类】发送短信失败，手机用户"+phone+"没有收到验证码！异常信息为：{}"+respMap.get(SmsConstants.SMS_RESPONSE_KEY_MESSAGE));
        } catch (ServerException e) {
            log.error("【阿里云短信工具类】发送短信失败，阿里云服务器异常！异常信息为：{}", e.getMessage());
            throw new LyException(ExceptionEnum.SEND_MESSAGE_ERROR);
        } catch (ClientException e) {
            log.error("【阿里云短信工具类】发送短信失败，乐优商城短信微服务异常！异常信息为：{}", e.getMessage());
            throw new LyException(ExceptionEnum.SEND_MESSAGE_ERROR);
        }
    }

}
